/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package familytree.persistencia.dao.hibernate;

import familytree.persistencia.dao.EventoDAO;
import familytree.persistencia.pojos.Evento;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Transaction;

/**
 *
 * @author Jose
 */
public class HibernateEventoDAO extends HibernateGenericDAO<Evento,String> implements EventoDAO{
    
    public void anadirEvento(Evento e){
        Transaction tx = getSession().beginTransaction();
        try{
            makePersistent(e);
            tx.commit();
        }
        catch(HibernateException ex){
            tx.rollback();
        }
    }
    
    public void actualizaEvento(Evento e){
        String nombre = e.getNombre();
        String idNodo = e.getNodo().getIdNodo();
        Transaction tx = getSession().beginTransaction();
        try{
            String sql= "SELECT ev.* from evento ev where ev.nombre = :nombre and ev.idNodo = :idNodo";
            SQLQuery query = getSession().createSQLQuery(sql);
            query.addEntity(Evento.class);
            query.setString("nombre",nombre);
            query.setString("idNodo",idNodo);
            List<Evento> l = new ArrayList<Evento>();
            l = query.list();
            Evento evento;
            if (!l.isEmpty()){
            evento = (Evento)l.get(0);
            evento.setFecha(e.getFecha());
            }
            else{
            evento = e;
            }
            this.makePersistent(evento);
            tx.commit();
        }
        catch(HibernateException ex){
         tx.rollback();
        }
    }
    
    public List<Evento> getEventosPorIdArbol(String idArbol){
        Transaction tx = getSession().beginTransaction();
        try{
            String sql = "select ev.* from evento ev inner join nodo n on n.idNodo = ev.idNodo where n.idArbol= :idArbol";
            SQLQuery query = getSession().createSQLQuery(sql);
            query.addEntity(Evento.class);
            query.setString("idArbol", idArbol);
            List<Evento> l = new ArrayList<Evento>();
            l=query.list();
            tx.commit();
            return l;
        }
        catch(HibernateException e){
            tx.rollback();
        }
        return null;
    }
}
